<?php
/**
 * Author: Nguyen Hoai Tan (nguoiao007@gmail.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'Shared/Models/Portal.php';
require_once 'Shared/Models/Category.php';
require_once 'Shared/Models/User.php';
//20110708
require_once 'Shared/Models/Scontent.php';
require_once 'Shared/Models/ScontentLang.php';
require_once 'Shared/Models/ScontentCategory.php';
//20110708
class portal_AdminController extends Vi_Controller_Action_Admin 
{

    public function managerAction()
    {
        $this->view->headTitle(Vi_Language::translate('Portal Manager'));
        $this->view->menu = array('portal', 'portalmanager');
        
        $config = Vi_Registry::getConfig();
        $numRowPerPage = Vi_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        /**
         * Get number of portal per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->portalDisplayNum;
        } else {
            $this->session->portalDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->portalCondition;
        } else {
            $this->session->portalCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        /**
         * Load all portals
         */
        $objPortal = new Models_Portal();
        $allPortals = $objPortal->getAllPortals($condition, 'portal_id DESC',
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
        /**
         * Count all portals
         */
        $count = count($objPortal->getAllPortals($condition));
        /**
         * Modify all portals
         */
        foreach ($allPortals as &$portal) {
            if (null != $portal['created_date']) {
                $portal['created_date'] = date($config['dateFormat'], $portal['created_date']);
            }
        }
        unset($portal);
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allPortals = $allPortals;
        $this->view->portalMessage = $this->session->portalMessage;
        $this->session->portalMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
    }
    

    public function newAction()
    {
        $this->view->headTitle(Vi_Language::translate('New Portal'));
        $this->view->menu = array('portal', 'portalnew');
        
        /**
         * Get data
         */
        $objPortal = new Models_Portal();
        $objUser = new Models_User();
        $data = $this->_getParam('data', false);
        $error = '';
        
        if (false != $data) {
            /**
             * Insert new portal
             */
            $newPortal = $data;
            $newPortal['created_date'] = time();
            $newPortal['enabled'] = 0;

            $objPortal->insert($newPortal);
            
            $this->session->portalMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('New portal is created successfully')
                                           );
            $this->_redirect('portal/admin/manager#listofportal');

        } 
        
        
        $this->view->data = $data;
        $this->view->error = $error;
        $this->view->users = $objUser->getByColumnName(array('group_id=?'=>2))->toArray();
    }
    

    public function deleteAction()
    {
        
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('portal/admin/manager');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objPortal = new Models_Portal();
        $objUser = new Models_User();
        try {
            foreach ($ids as $id) {
//                /**
//                 * Also delete account
//                 */
//                $res = $objPortal->find($id)->toArray();
//                $res = current($res);
//                
//                if (null != @$res['user_id']) {
//                    $objUser->delete(array('user_id=?' => $res['user_id']));
//                }
                
               $objPortal->delete( array('portal_id=?' => $id));
            }
            $this->session->portalMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Portal is deleted successfully')
                                           );
        } catch (Exception $e) {
            $this->session->portalMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can NOT delete this portal. Please try again')
                                           );
        }
        $this->_redirect('portal/admin/manager#listofportal');
    }

    
    public function enableAction()
    {
		$id = $this->_getParam('id', false);        
        if (false == $id) {
            $this->_redirect('portal/admin/manager');
        }
        
        $ids = explode('_', trim($id, '_'));
        
	    $objPortal = new Models_Portal();
	    //get generated of Portal
	    $Portal = $objPortal->getPortalbyId($id);
	    $Portal = current($Portal);
	    if(1 == $Portal['generated']) {
	        try {
	            foreach ($ids as $id) {
	               $objPortal->update(array('enabled' => 1), array('portal_id=?' => $id));
	            }
	            $this->session->portalMessage = array(
	                                               'success' => true,
	                                               'message' => Vi_Language::translate('Portal is enable successfully')
	                                           );
	        } catch (Exception $e) {
	            $this->session->portalMessage = array(
	                                               'success' => false,
	                                               'message' => Vi_Language::translate('Can NOT enable this portal. Please try again')
	                                           );
	        }
    	} else {
    		//port has not been generated yet
    		$this->session->portalMessage = array(
	                                               'success' => false,
	                                               'message' => Vi_Language::translate('Portal has not been generated yet')
	                                           );
    	}
    	$this->_redirect('portal/admin/manager#listofportal');
    }

    
    
    public function disableAction()
    {
        
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('portal/admin/manager');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objPortal = new Models_Portal();
        try {
            foreach ($ids as $id) {
               $objPortal->update(array('enabled' => 0), array('portal_id=?' => $id));
            }
            $this->session->portalMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Portal is disable successfully')
                                           );
        } catch (Exception $e) {
            $this->session->portalMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can NOT disable this portal. Please try again')
                                           );
        }
        $this->_redirect('portal/admin/manager#listofportal');
    }
    
    public function editAction()
    {
        $this->view->headTitle(Vi_Language::translate('Edit Portal'));
        $this->view->menu = array('portal');
        
        /**
         * Get data
         */
        $objPortal = new Models_Portal();
        $objUser = new Models_User();
        $data = $this->_getParam('data', false);
        $id   = $this->_getParam('id', false);
        $error = '';
        
        if (false === $id) {
            $this->_redirect('portal/admin/manager');
        }
        
        if (false != $data) {
            /**
             * Insert new portal
             */
            $newPortal = $data;
            $newPortal['created_date'] = time();
            $newPortal['image'] = $this->_getImagePath($newPortal['image']);

            $objPortal->update($newPortal, array('portal_id=?' => $id));
            
            $this->session->portalMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Portal is updated successfully')
                                           );
            $this->_redirect('portal/admin/manager#listofportal');

        } else {
            /**
             * Load default data
             */
            $data = $objPortal->find($id)->current();
            if (false == $data) {
                $this->_redirect('portal/admin/manager');
            }
            $data = $data->toArray();
        }
        
        
        $this->view->data = $data;
        $this->view->error = $error;
        $this->view->users = $objUser->getByColumnName(array('group_id=?'=>2))->toArray();
    }

     public function generateAction()
     {
     	$id   = $this->_getParam('id', false); 
     	$objPortal = new Models_Portal();
     	$objUser = new Models_User();
     	if ($this->getRequest()->isPost()) {
	     	//generate portal application
			$Portal = $objPortal->getPortalbyId($id);
			$Portal = current($Portal);
			$folderPath = "applications/" . $Portal['portal_alias'] . "/";
			$filePath = $folderPath . "config.php";
			$content = "<?php
						return array (
							'module' => array (
								'test' => 'test'
							),
							'layoutCollection' => 'default',
							'defaultLayout' => 'portal',
							'defaultModule' => 'default',
  							'defaultController' => 'portal',
  							'defaultAction' => 'index',						
						);";
			//note: the file path must be allowed to read/write
			if (!mkdir($folderPath, 0777, true)) {
				$this->session->portalMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can not create application folder')
                                           );
			}
			if( false == file_put_contents($filePath, $content)) {
				 $this->session->portalMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can not create file config')
                                           );
			} else {
				$this->session->portalMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Portal generated successfully')
                                           );
			}
     		//20110708
     			//set all scontents of the most recent generated portal to this generated portal
     			$recentPortal = $objPortal->GetRecentPortal();
     			$recentPortal = current($recentPortal);
     			$objScontent = new Models_Scontent();
     			$objScontentLang = new Models_ScontentLang();
     			$condition = array();
     			$condition['portal_id'] = $recentPortal['portal_id'];
     			$allScontentsBelongsToPortalId = $objScontent->getContentByPortalId($condition);
//     			echo '<pre>'; print_r($allScontentsBelongsToPortalId);die;
     			foreach($allScontentsBelongsToPortalId as $scontent) {
     				$scontent['portal_id'] = $id;
     				$newScontent = array(
                                'scontent_category_id' => $scontent['scontent_category_id'],
                				'portal_id'            => $scontent['portal_id'],
								'menu_id'	           => $scontent['menu_id'],               				
                                'enabled'              => $scontent['enabled'],
                                'publish_up_date'      => $scontent['publish_up_date'],
                                'publish_down_date'    => $scontent['publish_down_date'],
                                'sorting'              => $scontent['sorting'],
                				'enable_comment'       => $scontent['enable_comment'], 
                                'created_date'         => time()
                            );
     				$newScontentId = $objScontent->insert($newScontent);
     				$scontentLang = $objScontentLang->getContent($scontent['scontent_id']);
     				$newScontentLang = array(
                                'scontent_id'    => $newScontentId,
                                'lang_id'        => $scontentLang['lang_id'],
                                'enabled'        => $scontentLang['enabled'],
                                'title'          => $scontentLang['title'],
                                'category_alias' => $scontentLang['category_alias'],
                                'alias'          => $scontentLang['alias'],
                                'url'            => $scontentLang['url'],
                                'intro_text'     => $scontentLang['intro_text'],
                                'full_text'      => $scontentLang['full_text'],
                                'param'          => $scontentLang['param'],
                                'meta_data'      => $scontentLang['meta_data'],
                        		'enable_comment' => $scontentLang['enable_comment']
                                );
     				$objScontentLang->insert($newScontentLang);
     			}
     		//20110708
			$data = array();
	     	$data['enabled'] = 1;
	     	$data['generated'] = 1; 
	     	$objPortal->update($data, array('portal_id=?' => $id));
	     	
	     	$this->_redirect('portal/admin/manager#listofportal');
     	} else {
            /**
             * Load default data
             */
            $data = $objPortal->find($id)->current();
            if (false == $data) {
                $this->_redirect('portal/admin/manager');
            }
            $data = $data->toArray();
        }
        $this->view->data = $data;
        $this->view->users = current($objUser->getByColumnName(array('group_id=?'=>2))->toArray());
        
     }
    
    private function _getImagePath($path)
    {
        return substr($path, strlen(Vi_Registry::getBaseUrl()));
    }
    
}